#!/usr/bin/env bash

# Checks that the correct abigen is installed in this directory, and installs it
# if not.

set -e

# Version of abigen to install. Must be run within chainlink project
GETH_VERSION=$(go list -json -m github.com/ethereum/go-ethereum | jq -r .Version)
GETH_REPO_URL="https://github.com/ethereum/go-ethereum"

function realpath { echo $(cd $(dirname $1); pwd)/$(basename $1); }
THIS_DIR="$(realpath "$(dirname $0)")"

NATIVE_ABIGEN_VERSION=v"$(
    "$THIS_DIR/abigen" --version 2> /dev/null | \
    grep -E -o '([0-9]+\.[0-9]+\.[0-9]+)'
)" || true

if [ "$NATIVE_ABIGEN_VERSION" == "$GETH_VERSION" ]; then
    echo "Correct abigen version already installed."
    exit 0
fi

function cleanup() {
    rm -rf "$TMPDIR"
}

trap cleanup EXIT

TMPDIR="$(mktemp -d)"

pushd "$TMPDIR"

# We do not use go install here as we don't want the behavior to implicitly depend on user-configured variables like $PATH
git clone --depth=1 --single-branch --branch "$GETH_VERSION" "$GETH_REPO_URL"
cd go-ethereum/cmd/abigen
go build -ldflags="-s -w" # necessary on MacOS for code signing (see  https://github.com/confluentinc/confluent-kafka-go/issues/1092#issuecomment-2373681430)
rm -f "$THIS_DIR/abigen" # necessary on MacOS for code signing
cp ./abigen "$THIS_DIR"

popd

